package com.chkj.fbook.common.utils;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by hsh
 */
public class ComUtil {

    private static Logger log = LoggerFactory.getLogger(ComUtil.class);

    // 凭证获取（GET）
    //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET
    public final static String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code";

    public final static String send_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";

    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http://1223.applinzi.com/oauth2.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    public final static String userInfo_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE";

    /**
     * 发送https请求
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化

            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);

            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("连接超时：{}", ce);
        } catch (Exception e) {
            log.error("https请求异常：{}", e);
        }
        return jsonObject;
    }

    /**
     * 获取接口访问凭证
     *
     * @param corpid 凭证
     * @param corpsecret 密钥
     * @return
     */
    public static String getAccessToken(String corpid, String corpsecret) {
        String access_token = "";
        String requestUrl = token_url.replace("APPID", corpid).replace("APPSECRET", corpsecret);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                access_token = jsonObject.getString("access_token");
                log.info("access_token的值：{}", access_token);
                System.out.println("accessTokenUrl ================ access_token的值 : " + access_token);
            } catch (JSONException e) {
                access_token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return access_token;
    }

    public static String getUserId(String access_token, String code) {
        String UserId = "";
        String requestUrl = userInfo_url.replace("ACCESS_TOKEN", access_token).replace("CODE", code);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                UserId = jsonObject.getString("UserId");
                log.info("获取用户的UserId绑定的值：" + UserId);
                System.out.println("userInfoUrl ================ userId的值 : " + UserId);
            } catch (JSONException e) {
                UserId = null;
                // 获取UserId失败
                log.error("获取UserId失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return UserId;
    }

    public static String sendMsg(String accessToken, String outputStr) {
        String result = "";
        String requestUrl = send_url.replace("ACCESS_TOKEN", accessToken);

        JSONObject jsonObject = httpsRequest(requestUrl, "POST", outputStr);

        if (null != jsonObject) {
            try {
                result = jsonObject.getString("errcode");
            } catch (JSONException e) {
                result = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return result;
    }

    public static String getOpenid(String corpId, String secret, String code) {
//        String accessToken = getAccessToken(corpId, secret, code);
        String openid = getOpenId(corpId, secret, code);
        return openid;
    }

    private static String getAccessToken(String appId, String secret, String code) {
        String access_token = "";
        String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", secret).replace("CODE", code);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                access_token = jsonObject.getString("access_token");
                String openid = jsonObject.getString("openid");
                log.info("access_token的值：{}", access_token);
                System.out.println("accessTokenUrl ================ access_token的值 : " + access_token);
            } catch (JSONException e) {
                access_token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return access_token;
    }

    private static String getOpenId(String appId, String secret, String code) {
        String openid = "";
        String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", secret).replace("CODE", code);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                openid = jsonObject.getString("openid");
                log.info("openid：{}", openid);
                System.out.println("accessTokenUrl ================ openid : " + openid);
            } catch (JSONException e) {
                openid = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return openid;
    }

    /**
     * 向指定的地址发送一个post请求，带着data数据
     * @param url
     * @param data
     * @return
     */
    public static String post(String url, String data) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            //要发送数据出去，必须要设置为可发送数据状态
            connection.setDoOutput(true);
            //获取输出流
            OutputStream os = connection.getOutputStream();
            //写出数据
            os.write(data.getBytes());
            os.close();
            //获取输入流
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向指定的url发起一个get请求获取数据
     * @param url
     * @return
     */
    public static String get(String url) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
